package com.msb.unitil;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @version : 1.0
 * @Author: yangmingsong
 * @Date: 2021/2/3-02-03-21:13
 * @Description: demon
 */
public class DBUnitil {
    private static ThreadLocal<SqlSession> sl = new ThreadLocal<>();
     private static SqlSessionFactory build;
    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybaties.xml");
            build = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getsqlsession(){
        SqlSession sqlSession = sl.get();
        if(sqlSession==null){
            sqlSession = build.openSession(true);
            sl.set(sqlSession);
        }
        return sl.get();
    }
    public static void closeAll(){
        SqlSession sqlSession = sl.get();
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
